package com.shark.uh.utils;

import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class UrlParser {

    public static Map<String, Object> parseUrl(String urlString) {
        Map<String, Object> result = new HashMap<>();

        try {
            URL url = new URL(urlString);

            // 获取各个部分
            String protocol = url.getProtocol();
            String host = url.getHost();
            String path = url.getPath();
            String query = url.getQuery();
            String ref = url.getRef();

            // 存储到结果中
            result.put("fullUrl", urlString);
            result.put("protocol", protocol);
            result.put("host", host);
            result.put("pathname", path);
            result.put("hash", ref);

            // 如果有查询参数
            if (query != null) {
                Map<String, String> params = new HashMap<>();
                String[] queryParams = query.split("&");

                for (String param : queryParams) {
                    String[] keyValue = param.split("=");
                    if (keyValue.length == 2) {
                        // 解码URL编码的参数值
                        String key = keyValue[0];
                        String value = URLDecoder.decode(keyValue[1], "UTF-8");
                        params.put(key, value);
                    }
                }
                result.put("searchParams", params);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    // 只返回查询参数的Map
    public static Map<String, String> getQueryParams(String urlString) {
        Map<String, String> queryParams = new HashMap<>();

        try {
            URL url = new URL(urlString);
            String query = url.getQuery();

            if (query != null) {
                String[] queryParamsArray = query.split("&");

                for (String param : queryParamsArray) {
                    String[] keyValue = param.split("=");
                    if (keyValue.length == 2) {
                        // 解码URL编码的参数值
                        String key = keyValue[0];
                        String value = URLDecoder.decode(keyValue[1], "UTF-8");
                        queryParams.put(key, value);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return queryParams;
    }


}
